package com.whh.permission.controller;

import com.whh.permission.po.Role;
import com.whh.permission.service.IRoleService;
import com.whh.permission.util.JsonObject;
import com.whh.permission.util.R;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
public class RoleController {
    @Resource
    private IRoleService roleServiceImpl;

    /**
     * 查询所有的角色信息
     */
    @RequestMapping("role/roleAll")
    @ResponseBody
    public JsonObject queryRoleAll(){
        JsonObject object = new JsonObject();
        List<Role> roles = roleServiceImpl.queryRoleAll();
        object.setCode(200);
        object.setData(roles);
        object.setCount((long) roles.size());
        object.setMsg("ok");
        return object;
    }


    /**
     * 角色主页跳转
     */
    @RequestMapping("role")
    public String roleMenu(){
        return "pages/role";
    }

    /**
     * 添加跳转页
     */
    @RequestMapping("/addRole")
    public String addRole (Model model, Integer parentId){
        model.addAttribute("parentId",parentId);
        return "pages/addRole";
    }

    /**
     * 添加功能实现
     * @param role
     * @return
     */
    @RequestMapping("role/addRoleSubmit")
    @ResponseBody
    public R addRole(Role role){
        role.setCreateTime(new Date());
        roleServiceImpl.addRole(role);
        return R.ok();
    }

    /**删除功能
     *
     */
    @RequestMapping("role/deleteRoleById")
    @ResponseBody
    public R deleteRoleById(Integer id){
        roleServiceImpl.deleteRoleById(id);
        return R.ok();
    }

    /**
     * 添加关联权限跳转页面
     */
    @RequestMapping("/addPerm")
    public String addPerm(Model model,int id){
        model.addAttribute("roleId",id);
        return "pages/addPerm";
    }

    /**
     * 添加关联角色权限
     */
    @RequestMapping("role/addPermSubmit")
    @ResponseBody
    public R addPermSubmit(int[] ids,int roleId){       //ids是menuIds
        //调用service
        roleServiceImpl.insertForEach(ids,roleId);
        return R.ok();
    }

    /**
     * 进行角色修改的页面跳转
     */
    @RequestMapping("role/queryRoleById")
    public String updateRole(Model model,int id){
        //根据id查询信息返回前台
        Role role = roleServiceImpl.queryRoleById(id);
        model.addAttribute("role",role);
        return "pages/updateRole";
    }

    /**
     * 角色修改功能
     */
    @RequestMapping("role/updateRoleSubmit")
    @ResponseBody
    public R updateRole(Role role){
        role.setUpdateTime(new Date());
//        System.out.println(role);
        roleServiceImpl.updateRole(role);
        return R.ok();
    }

    /**
     * 角色树结构的渲染工作
     */
    @RequestMapping("queryRoleTree")
    @ResponseBody
    public Object queryDeptTree(){
        return roleServiceImpl.queryRoleTree();
    }
}
